<template>
  <div class="production-orders-container">
    <div class="page-header">
      <h2>生产订单管理</h2>
      <button class="btn btn-primary" @click="showCreateModal = true">
        新增生产订单
      </button>
    </div>

    <!-- 筛选条件 -->
    <div class="filter-section">
      <div class="filter-item">
        <label>订单状态:</label>
        <select v-model="filters.status">
          <option value="">全部</option>
          <option value="CREATED">已创建</option>
          <option value="IN_PROGRESS">生产中</option>
          <option value="COMPLETED">已完成</option>
          <option value="CANCELLED">已取消</option>
        </select>
      </div>
      <div class="filter-item">
        <label>产品:</label>
        <select v-model="filters.product_id">
          <option value="">全部产品</option>
          <option 
            v-for="product in products" 
            :key="product.id" 
            :value="product.id"
          >
            {{ product.name }}
          </option>
        </select>
      </div>
      <button class="btn btn-secondary" @click="fetchOrders">查询</button>
    </div>

    <!-- 订单列表 -->
    <div class="table-container">
      <table class="data-table">
        <thead>
          <tr>
            <th>订单号</th>
            <th>产品</th>
            <th>数量</th>
            <th>计划开始时间</th>
            <th>计划完成时间</th>
            <th>实际完成时间</th>
            <th>状态</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="order in productionStore.orders" :key="order.id">
            <td>{{ order.order_no }}</td>
            <td>{{ order.product?.name }}</td>
            <td>{{ order.quantity }}</td>
            <td>{{ formatDate(order.planned_start_date) }}</td>
            <td>{{ formatDate(order.planned_completion_date) }}</td>
            <td>{{ order.actual_completion_date ? formatDate(order.actual_completion_date) : '-' }}</td>
            <td>
              <span :class="['status-badge', order.status.toLowerCase()]">
                {{ getStatusText(order.status) }}
              </span>
            </td>
            <td>{{ formatDateTime(order.created_at) }}</td>
            <td>
              <button class="btn btn-sm btn-info" @click="viewOrder(order)">
                查看
              </button>
              <button 
                v-if="order.status === 'CREATED'" 
                class="btn btn-sm btn-success" 
                @click="startOrder(order)"
              >
                开始生产
              </button>
              <button 
                v-if="order.status === 'IN_PROGRESS'" 
                class="btn btn-sm btn-warning" 
                @click="completeOrder(order)"
              >
                完成生产
              </button>
              <button 
                v-if="order.status === 'CREATED'" 
                class="btn btn-sm btn-danger" 
                @click="cancelOrder(order)"
              >
                取消
              </button>
            </td>
          </tr>
          <tr v-if="productionStore.orders.length === 0">
            <td colspan="9" class="text-center">暂无数据</td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 新增订单模态框 -->
    <div v-if="showCreateModal" class="modal-overlay" @click="showCreateModal = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>新增生产订单</h3>
          <button class="modal-close" @click="showCreateModal = false">&times;</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="createOrder">
            <div class="form-group">
              <label>产品:</label>
              <select v-model="newOrder.product_id" required>
                <option value="">请选择产品</option>
                <option 
                  v-for="product in products" 
                  :key="product.id" 
                  :value="product.id"
                >
                  {{ product.name }}
                </option>
              </select>
            </div>
            <div class="form-group">
              <label>数量:</label>
              <input type="number" v-model="newOrder.quantity" min="1" required />
            </div>
            <div class="form-row">
              <div class="form-group">
                <label>计划开始时间:</label>
                <input type="date" v-model="newOrder.planned_start_date" required />
              </div>
              <div class="form-group">
                <label>计划完成时间:</label>
                <input type="date" v-model="newOrder.planned_completion_date" required />
              </div>
            </div>
            <div class="form-group">
              <label>备注:</label>
              <textarea v-model="newOrder.remarks" rows="3"></textarea>
            </div>
          </form>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="showCreateModal = false">取消</button>
          <button class="btn btn-primary" @click="createOrder">保存</button>
        </div>
      </div>
    </div>

    <!-- 查看订单详情模态框 -->
    <div v-if="showDetailModal" class="modal-overlay" @click="showDetailModal = false">
      <div class="modal-content detail-modal" @click.stop>
        <div class="modal-header">
          <h3>生产订单详情</h3>
          <button class="modal-close" @click="showDetailModal = false">&times;</button>
        </div>
        <div class="modal-body" v-if="productionStore.currentOrder">
          <div class="order-info">
            <div class="info-row">
              <span class="label">订单号:</span>
              <span>{{ productionStore.currentOrder.order_no }}</span>
            </div>
            <div class="info-row">
              <span class="label">产品:</span>
              <span>{{ productionStore.currentOrder.product?.name }}</span>
            </div>
            <div class="info-row">
              <span class="label">数量:</span>
              <span>{{ productionStore.currentOrder.quantity }}</span>
            </div>
            <div class="info-row">
              <span class="label">计划开始时间:</span>
              <span>{{ formatDate(productionStore.currentOrder.planned_start_date) }}</span>
            </div>
            <div class="info-row">
              <span class="label">计划完成时间:</span>
              <span>{{ formatDate(productionStore.currentOrder.planned_completion_date) }}</span>
            </div>
            <div class="info-row">
              <span class="label">实际完成时间:</span>
              <span>{{ productionStore.currentOrder.actual_completion_date ? formatDate(productionStore.currentOrder.actual_completion_date) : '-' }}</span>
            </div>
            <div class="info-row">
              <span class="label">状态:</span>
              <span>
                <span :class="['status-badge', productionStore.currentOrder.status.toLowerCase()]">
                  {{ getStatusText(productionStore.currentOrder.status) }}
                </span>
              </span>
            </div>
            <div class="info-row">
              <span class="label">创建时间:</span>
              <span>{{ formatDateTime(productionStore.currentOrder.created_at) }}</span>
            </div>
            <div class="info-row">
              <span class="label">备注:</span>
              <span>{{ productionStore.currentOrder.remarks || '-' }}</span>
            </div>
          </div>
          
          <!-- 物料清单 -->
          <div class="bom-section" v-if="productionStore.currentOrder.product?.bom_items?.length">
            <h4>物料清单</h4>
            <table class="data-table">
              <thead>
                <tr>
                  <th>原材料</th>
                  <th>单位用量</th>
                  <th>总需求量</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="bomItem in productionStore.currentOrder.product.bom_items" :key="bomItem.id">
                  <td>{{ bomItem.material?.name }}</td>
                  <td>{{ bomItem.quantity_per_unit }}</td>
                  <td>{{ bomItem.quantity_per_unit * productionStore.currentOrder.quantity }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { useProductionStore } from '@/stores/production'
import { format } from 'date-fns'

export default {
  name: 'ProductionOrders',
  setup() {
    const productionStore = useProductionStore()
    
    // 状态
    const showCreateModal = ref(false)
    const showDetailModal = ref(false)
    const products = ref([])
    
    // 筛选条件
    const filters = reactive({
      status: '',
      product_id: ''
    })
    
    // 新增订单数据
    const newOrder = reactive({
      product_id: '',
      quantity: 1,
      planned_start_date: format(new Date(), 'yyyy-MM-dd'),
      planned_completion_date: format(new Date(new Date().setDate(new Date().getDate() + 7)), 'yyyy-MM-dd'),
      remarks: ''
    })
    
    // 方法
    const fetchOrders = async () => {
      try {
        await productionStore.fetchOrders(filters)
      } catch (error) {
        console.error('获取生产订单失败:', error)
        alert('获取生产订单失败: ' + (error.message || '未知错误'))
      }
    }
    
    const fetchProducts = async () => {
      try {
        const response = await productionStore.fetchProducts()
        products.value = response.data || []
      } catch (error) {
        console.error('获取产品列表失败:', error)
        alert('获取产品列表失败: ' + (error.message || '未知错误'))
      }
    }
    
    const createOrder = async () => {
      try {
        await productionStore.createOrder({
          product_id: newOrder.product_id,
          quantity: newOrder.quantity,
          planned_start_date: newOrder.planned_start_date,
          planned_completion_date: newOrder.planned_completion_date,
          remarks: newOrder.remarks
        })
        
        showCreateModal.value = false
        resetNewOrder()
        await fetchOrders()
        alert('生产订单创建成功')
      } catch (error) {
        console.error('创建生产订单失败:', error)
        alert('创建生产订单失败: ' + (error.message || '未知错误'))
      }
    }
    
    const viewOrder = async (order) => {
      try {
        await productionStore.fetchOrderDetail(order.id)
        showDetailModal.value = true
      } catch (error) {
        console.error('获取订单详情失败:', error)
        alert('获取订单详情失败: ' + (error.message || '未知错误'))
      }
    }
    
    const startOrder = async (order) => {
      if (!confirm('确定要开始该生产订单吗？')) return
      
      try {
        await productionStore.updateOrderStatus(order.id, 'IN_PROGRESS')
        await fetchOrders()
        alert('订单状态已更新为生产中')
      } catch (error) {
        console.error('更新订单状态失败:', error)
        alert('更新订单状态失败: ' + (error.message || '未知错误'))
      }
    }
    
    const completeOrder = async (order) => {
      if (!confirm('确定要完成该生产订单吗？')) return
      
      try {
        await productionStore.updateOrderStatus(order.id, 'COMPLETED')
        await fetchOrders()
        alert('订单状态已更新为已完成')
      } catch (error) {
        console.error('更新订单状态失败:', error)
        alert('更新订单状态失败: ' + (error.message || '未知错误'))
      }
    }
    
    const cancelOrder = async (order) => {
      if (!confirm('确定要取消该生产订单吗？')) return
      
      try {
        await productionStore.updateOrderStatus(order.id, 'CANCELLED')
        await fetchOrders()
        alert('订单已取消')
      } catch (error) {
        console.error('取消订单失败:', error)
        alert('取消订单失败: ' + (error.message || '未知错误'))
      }
    }
    
    const resetNewOrder = () => {
      newOrder.product_id = ''
      newOrder.quantity = 1
      newOrder.planned_start_date = format(new Date(), 'yyyy-MM-dd')
      newOrder.planned_completion_date = format(new Date(new Date().setDate(new Date().getDate() + 7)), 'yyyy-MM-dd')
      newOrder.remarks = ''
    }
    
    const getStatusText = (status) => {
      const statusMap = {
        'CREATED': '已创建',
        'IN_PROGRESS': '生产中',
        'COMPLETED': '已完成',
        'CANCELLED': '已取消'
      }
      return statusMap[status] || status
    }
    
    const formatDate = (dateString) => {
      if (!dateString) return ''
      return format(new Date(dateString), 'yyyy-MM-dd')
    }
    
    const formatDateTime = (dateString) => {
      if (!dateString) return ''
      return format(new Date(dateString), 'yyyy-MM-dd HH:mm:ss')
    }
    
    // 初始化
    onMounted(async () => {
      await Promise.all([
        fetchOrders(),
        fetchProducts()
      ])
    })
    
    return {
      productionStore,
      showCreateModal,
      showDetailModal,
      filters,
      newOrder,
      products,
      fetchOrders,
      createOrder,
      viewOrder,
      startOrder,
      completeOrder,
      cancelOrder,
      getStatusText,
      formatDate,
      formatDateTime
    }
  }
}
</script>

<style scoped>
.production-orders-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h2 {
  margin: 0;
}

.filter-section {
  display: flex;
  gap: 15px;
  margin-bottom: 20px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 4px;
}

.filter-item {
  display: flex;
  align-items: center;
  gap: 5px;
}

.filter-item label {
  white-space: nowrap;
}

.table-container {
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  background: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.data-table th,
.data-table td {
  padding: 12px 15px;
  text-align: left;
  border-bottom: 1px solid #dee2e6;
}

.data-table th {
  background-color: #f8f9fa;
  font-weight: 600;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.created {
  background-color: #17a2b8;
  color: white;
}

.status-badge.in_progress {
  background-color: #ffc107;
  color: #212529;
}

.status-badge.completed {
  background-color: #28a745;
  color: white;
}

.status-badge.cancelled {
  background-color: #dc3545;
  color: white;
}

.btn {
  padding: 8px 16px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-primary {
  background-color: #007bff;
  color: white;
}

.btn-primary:hover {
  background-color: #0056b3;
}

.btn-secondary {
  background-color: #6c757d;
  color: white;
}

.btn-secondary:hover {
  background-color: #545b62;
}

.btn-success {
  background-color: #28a745;
  color: white;
}

.btn-success:hover {
  background-color: #1e7e34;
}

.btn-info {
  background-color: #17a2b8;
  color: white;
}

.btn-info:hover {
  background-color: #117a8b;
}

.btn-warning {
  background-color: #ffc107;
  color: #212529;
}

.btn-warning:hover {
  background-color: #e0a800;
}

.btn-danger {
  background-color: #dc3545;
  color: white;
}

.btn-danger:hover {
  background-color: #bd2130;
}

.btn-sm {
  padding: 4px 8px;
  font-size: 12px;
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 800px;
  max-height: 90vh;
  overflow-y: auto;
}

.detail-modal {
  max-width: 1000px;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #dee2e6;
}

.modal-header h3 {
  margin: 0;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #6c757d;
}

.modal-body {
  padding: 24px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
  padding: 16px 24px;
  border-top: 1px solid #dee2e6;
}

.form-group {
  margin-bottom: 15px;
}

.form-group label {
  display: block;
  margin-bottom: 5px;
  font-weight: 500;
}

.form-group input,
.form-group select,
.form-group textarea {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #ced4da;
  border-radius: 4px;
  font-size: 14px;
}

.form-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 15px;
}

.order-info {
  margin-bottom: 20px;
}

.info-row {
  display: flex;
  margin-bottom: 10px;
}

.info-row .label {
  width: 120px;
  font-weight: 500;
}

.bom-section {
  margin-top: 20px;
}

.bom-section h4 {
  margin-bottom: 15px;
  border-bottom: 1px solid #dee2e6;
  padding-bottom: 5px;
}

.text-center {
  text-align: center;
}
</style>